<template>
  <div>
    <!-- 面包屑 -->
    <bread></bread>
    <el-card>
      <el-button type="primary" @click="addCate">添加分类</el-button>
      <!-- 表格 -->
      <el-table
        :data="categoriesData"
        style="width: 100%; margin-bottom: 20px"
        row-key="cat_id"
        border
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="cat_name" label="分类名称"></el-table-column>
        <el-table-column label="是否有效">
          <template v-slot="scope">
            <i
              class="el-icon-success"
              v-show="scope.row.cat_deleted === false"
              style="color: green"
            ></i>
            <i
              class="el-icon-success"
              v-show="scope.row.cat_deleted === true"
              style="color: red"
            ></i>
          </template>
        </el-table-column>
        <el-table-column prop="cat_level" label="排序">
          <template slot-scope="scope">
            <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
            <el-tag size="mini" type="success" v-else-if="scope.row.cat_level === 1"
              >二级</el-tag
            >
            <el-tag size="mini" type="warning" v-else>三级</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="updata(scope.row.cat_id, scope.row.cat_name)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="remove(scope.row.cat_id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--分页-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="this.totals"
      >
      </el-pagination>

      <!-- 添加 -->
      <el-dialog title="添加分类" :visible.sync="dialogFormVisible">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="ruleForm.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类">
            <!-- 级联选择器 -->
            <el-cascader
              v-model="value"
              :options="options"
              :props="keyname"
              @change="handleChange"
            ></el-cascader>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 编辑 -->
      <el-dialog title="修改分类" :visible.sync="updataVisible" label-width="100px">
        <el-form :model="updataInfo" :rules="rules" ref="updataInfo" label-width="100px">
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="updataInfo.cat_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="updataVisible = false">取 消</el-button>
          <el-button type="primary" @click="updataCate('updataInfo')">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import bread from "../bread";
export default {
  components: { bread },
  data() {
    return {
      // 所有数据
      categoriesData: [],
      // 获取数据的参数
      queryInfo: {
        type: "",
        pagenum: null,
        pagesize: null,
      },
      totals: 0,
      //添加框数据
      dialogFormVisible: false,
      ruleForm: {
        cat_name: "", //分类名称
        cat_pid: 0, //父id
        // 分类的层级
        cat_level: 0,
      },
      rules: {
        cat_name: [{ required: true, message: "分类名称不能为空", trigger: "blur" }],
      },
      value: [],
      // 级联选择器数据
      options: [],

      // 级联选择器参数
      keyname: {
        checkStrictly: true,
        expandTrigger: "hover", // 次级菜单的展开方式
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },

      // 编辑数据
      updataVisible: false,
      updataInfo: {
        cat_id: "",
        cat_name: "",
      },
    };
  },
  mounted() {
    this.getData();
  },
  methods: {
    // 获取数据
    async getData() {
      let res = await this.$axios.get("categories", {
        params: this.queryInfo,
      });
      this.categoriesData = res.data;
      this.totals = res.data.length;
    },

    // 分页
    handleSizeChange(val) {
      this.queryInfo.pagesize = val; //每页条
      this.getData();
    },
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val; //当前页
      this.getData();
    },

    // 添加
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        console.log(valid);
        if (valid) {
          this.$axios.post("categories", this.ruleForm).then((res) => {
            if (res.meta.status !== 201) {
              this.$message.error(res.meta.msg);
            } else {
              this.$message.success(res.meta.msg);
              this.getData();
              this.dialogFormVisible = false;
              this.ruleForm = {};
              this.value = [];
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 获取级联数据
    addCate() {
      this.$axios.get("/categories", { params: { type: 2 } }).then((res) => {
        const { data, meta } = res;
        if (meta.status !== 200) {
          this.$message.error(meta.msg);
        } else {
          this.options = data;
        }
      });
      this.dialogFormVisible = true;
    },
    // 分级
    handleChange() {
      if (this.value.length === 0) {
        this.ruleForm.cat_pid = 0;
        this.ruleForm.cat_level = 0;
      } else {
        this.ruleForm.cat_pid = this.value[this.value.length - 1];
        this.ruleForm.cat_level = this.value.length;
      }
    },
    // 删除
    remove(id) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios
            .delete("categories/" + id, {
              params: { cat_id: id },
            })
            .then((res) => {
              if (res.meta.status == 200) {
                this.getData();
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 获取编辑数据
    updata(id, name) {
      this.updataVisible = true;
      this.updataInfo.cat_id = id;
      this.updataInfo.cat_name = name;
    },

    // 刷新编辑数据
    updataCate(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let res = await this.$axios.put(
            "categories/" + this.updataInfo.cat_id,
            this.updataInfo
          );
          if (res.meta.status !== 200) {
            this.$message.error(res.meta.msg);
          } else {
            this.$message.success(res.meta.msg);
            this.updataVisible = false;
            this.getData();
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
  computed: {},
  watch: {},
};
</script>
